package com.android.scanner.barcode;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Timer;
import java.util.TimerTask;

import com.android.scanner.R;

import android.serialport.SerialPort;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.TextView.OnEditorActionListener;

public class BarcodeDemoActivity extends Activity {
    /** Called when the activity is first created. */
	
	
    public static final int KEY_SCAN = 111;
    public static final int KEY_F1 = 112;
    public static final int KEY_F2 = 113;
    public static final int KEY_F3 = 114;
    public static final int KEY_F4 = 115;
    private int KEY_POSITION = 0;
	
	private DeviceControl DevCtrl;
	private SerialPort mSerialPort;
	private String str = new String();
	private String buff = new String();
	public int fd;
	private ReadThread mReadThread;
	private Button close;
	private Button scan;
	private Button clearscreen;
	private EditText mReception;
	private EditText Emission;
	private Handler handler = null;
	private static final String TAG = "SerialPort";
	private boolean key_start = true;
	private boolean Powered = false;
	private boolean Opened = false;
	private Timer timer = new Timer();
	private Timer retrig_timer = new Timer();
	private SoundPool soundPool;
	private	int soundId;
	private Handler t_handler = null;
	private Handler n_handler = null;
	private boolean ops = false;
	
	private Spinner					spinner;
	private ArrayAdapter<CharSequence>	adapter;
	
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.barcode);
        mReception = (EditText) findViewById(R.id.EditTextReception);
        Emission = (EditText) findViewById(R.id.EditTextEmission);
        close = (Button) this.findViewById(R.id.buttonclose);
        close.setOnClickListener(new ClickEvent()); 
        scan = (Button) this.findViewById(R.id.buttonscan);
        scan.setOnClickListener(new ClickEvent()); 
        clearscreen = (Button)findViewById(R.id.buttonclear);
        clearscreen.setOnClickListener(new ClickEvent());
        spinner = (Spinner) findViewById(R.id.spinner);
        
        adapter = ArrayAdapter.createFromResource(
                this, R.array.choose_key, android.R.layout.simple_spinner_item);
        
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        
        spinner.setAdapter(adapter); 
        
        try {
        	DevCtrl = new DeviceControl("/proc/driver/scan");
			
		} catch (SecurityException e) {
			e.printStackTrace();
		} catch (IOException e) {
			Log.d(TAG, "AAA");
        	new AlertDialog.Builder(this).setTitle(R.string.DIA_ALERT).setMessage(R.string.DEV_OPEN_ERR).setPositiveButton(R.string.DIA_CHECK, new DialogInterface.OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
					finish();
				}
			}).show();
        	return;
		}
        ops = true;
        
       
        spinner.setOnItemSelectedListener(
                new OnItemSelectedListener() {
                    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                    	KEY_POSITION = position;
                    }

                    public void onNothingSelected(AdapterView<?> parent) {
                    }
                });
        
        
        Emission.setOnEditorActionListener(new OnEditorActionListener() {
			public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
				int i;
				CharSequence t = v.getText();
				char[] text = new char[t.length()];
				for (i=0; i<t.length(); i++) {
					text[i] = t.charAt(i);
				}
				str = new String(text);
				mSerialPort.WriteSerialString(fd, str,str.length());
				v.setText("");
				return false;
			}
		});
        
        soundPool = new SoundPool(1, AudioManager.STREAM_MUSIC, 0);
        soundId = soundPool.load("/system/media/audio/ui/VideoRecord.ogg", 0);
	    
        t_handler = new Handler() {
        	@Override
        	public void handleMessage(Message msg) {
        		super.handleMessage(msg);
        		if(msg.what == 1) {
        			try {
        				DevCtrl.PowerOffDevice();
        			} catch (IOException e) {
        				Log.d(TAG, "BBB");
						// TODO Auto-generated catch block
        				e.printStackTrace();
        			}//powersave
        			Powered = false;
        		}
        	}
        };
        
        n_handler = new Handler() {
        	@Override
        	public void handleMessage(Message msg) {
        		super.handleMessage(msg);
        		if(msg.what == 1) {
            	try {
            			if(key_start == false)
            			{
            				DevCtrl.TriggerOffDevice();
            				timer = new Timer();				//start a timer, when machine is idle for some time, cut off power to save energy.
            				timer.schedule(new MyTask(), 60000);
            				scan.setEnabled(true);
            				key_start = true;
            			}
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
        		}
        	}
        };
        
		handler = new Handler() {
			 
	            @Override
	            public void handleMessage(Message msg) {
	                super.handleMessage(msg);
	                if(msg.what == 1 && key_start == false){
	                    mReception.append(buff);
	                    soundPool.play(soundId, 1, 1, 0, 0, 1);
            			key_start = true;
           				scan.setEnabled(true);
           				retrig_timer.cancel();
	                }
	            }
	    };
    }
    
    class MyTask extends TimerTask
    {

		@Override
		public void run() {
			// TODO Auto-generated method stub
			Message message = new Message();
			message.what = 1;
			t_handler.sendMessage(message);
		}
    }
    
    class RetrigTask extends TimerTask
    {
		@Override
		public void run() {
			// TODO Auto-generated method stub
			Message message = new Message();
			message.what = 1;
			n_handler.sendMessage(message);
		}
    }
    
	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		if(ops == true)
		{
        mReadThread.interrupt();
        timer.cancel();
        retrig_timer.cancel();
       	try {
       		DevCtrl.PowerOffDevice();
			Thread.sleep(1000);
		} catch (IOException e) {
     		Log.d(TAG, "CCC");
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
       	Powered = false;
       	if(Opened == true)
       	{
       		mSerialPort.CloseSerial(fd);
       		Opened = false;
       	}
		}
    	Log.d(TAG, "onPause");
		super.onPause();
	}
	
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		if(ops == true)
		{
		if(Opened == false) {
			try {
				//mSerialPort = new SerialPort("/dev/eser1",9600);//3a
				mSerialPort = new SerialPort();//("/dev/eser0",9600);//35
				mSerialPort.OpenSerial("/dev/eser0",9600);
			} catch (SecurityException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				Log.d(TAG, "DDD");
				// TODO Auto-generated catch block
				e.printStackTrace();
				new AlertDialog.Builder(this).setTitle(R.string.DIA_ALERT).setMessage(R.string.DEV_OPEN_ERR).setPositiveButton(R.string.DIA_CHECK, new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
					finish();
					}
				}).show();
				ops = false;
				soundPool.release();
				try {
					DevCtrl.DeviceClose();
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				super.onResume();
				return;
			}
			fd = mSerialPort.getFd();
			if(fd > 0){
				Log.d(TAG,"opened");
				Opened = true;
			}
		}
		mReadThread = new ReadThread();
		mReadThread.start();
		}
    	Log.d(TAG, "onResume");
		super.onResume();
	}
    
    public void onDestroy() {
		// TODO Auto-generated method stub
    	if(ops == true)
    	{
    		try {
    			soundPool.release();
    			DevCtrl.DeviceClose();
    		} catch (IOException e) {
    			Log.d(TAG, "EEE");
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
    	}
		super.onDestroy();
	}
    
    class ClickEvent implements View.OnClickListener {  
        
        @Override  
        public void onClick(View v) {  
            if (v == close) {
            	BarcodeDemoActivity.this.finish();
            	}
            else if(v == scan)
            {
            	try {
            		if(key_start == true)
            		{
            			if(Powered == false)
            			{
            				Powered = true;
            				DevCtrl.PowerOnDevice();
            			}
           				timer.cancel();
           				DevCtrl.TriggerOnDevice();
						scan.setEnabled(false);
						key_start = false;
						retrig_timer = new Timer();
						retrig_timer.schedule(new RetrigTask(), 3500);	//start a timer, if the data is not received within a period of time, stop the scan.
            		}
				} catch (IOException e) {
					Log.d(TAG, "FFF");
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
            }
            else if(v == clearscreen)
            {
            	mReception.setText("");
            }
        }  
    }  
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode) {
        	case KEY_SCAN:
        		if(KEY_POSITION == 0){
	            	try {
	            		if(key_start == true)
	            		{
	            			if(Powered == false)
	            			{
	            				Powered = true;
	            				DevCtrl.PowerOnDevice();
	            			}
	           				timer.cancel();
	           				DevCtrl.TriggerOnDevice();
							scan.setEnabled(false);
							key_start = false;
							retrig_timer = new Timer();
							retrig_timer.schedule(new RetrigTask(), 3500);	//start a timer, if the data is not received within a period of time, stop the scan.
	            		}
					} catch (IOException e) {
						Log.d(TAG, "FFF");
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
        		}
            	break;
        	case KEY_F1:
        		if(KEY_POSITION == 1){
	        		try {
	            		if(key_start == true)
	            		{
	            			if(Powered == false)
	            			{
	            				Powered = true;
	            				DevCtrl.PowerOnDevice();
	            			}
	           				timer.cancel();
	           				DevCtrl.TriggerOnDevice();
							scan.setEnabled(false);
							key_start = false;
							retrig_timer = new Timer();
							retrig_timer.schedule(new RetrigTask(), 3500);	//start a timer, if the data is not received within a period of time, stop the scan.
	            		}
					} catch (IOException e) {
						Log.d(TAG, "FFF");
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
        		}
            	break;
        	case KEY_F2:
        		if(KEY_POSITION == 2){
	        		try {
	            		if(key_start == true)
	            		{
	            			if(Powered == false)
	            			{
	            				Powered = true;
	            				DevCtrl.PowerOnDevice();
	            			}
	           				timer.cancel();
	           				DevCtrl.TriggerOnDevice();
							scan.setEnabled(false);
							key_start = false;
							retrig_timer = new Timer();
							retrig_timer.schedule(new RetrigTask(), 3500);	//start a timer, if the data is not received within a period of time, stop the scan.
	            		}
					} catch (IOException e) {
						Log.d(TAG, "FFF");
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
        		}
            	break;
        	case KEY_F3:
        		if(KEY_POSITION == 3){
	        		try {
	            		if(key_start == true)
	            		{
	            			if(Powered == false)
	            			{
	            				Powered = true;
	            				DevCtrl.PowerOnDevice();
	            			}
	           				timer.cancel();
	           				DevCtrl.TriggerOnDevice();
							scan.setEnabled(false);
							key_start = false;
							retrig_timer = new Timer();
							retrig_timer.schedule(new RetrigTask(), 3500);	//start a timer, if the data is not received within a period of time, stop the scan.
	            		}
					} catch (IOException e) {
						Log.d(TAG, "FFF");
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
        		}
            	break;
        	case KEY_F4:
        		if(KEY_POSITION == 4){
	        		try {
	            		if(key_start == true)
	            		{
	            			if(Powered == false)
	            			{
	            				Powered = true;
	            				DevCtrl.PowerOnDevice();
	            			}
	           				timer.cancel();
	           				DevCtrl.TriggerOnDevice();
							scan.setEnabled(false);
							key_start = false;
							retrig_timer = new Timer();
							retrig_timer.schedule(new RetrigTask(), 3500);	//start a timer, if the data is not received within a period of time, stop the scan.
	            		}
					} catch (IOException e) {
						Log.d(TAG, "FFF");
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
        		}
            	break;
        }
        
        return super.onKeyDown(keyCode, event);
    }
    
    private class ReadThread extends Thread {

		@Override
		public void run() {
			super.run();
			while(!isInterrupted()) {
				try {
					Log.d(TAG,"read");
					buff = mSerialPort.ReadSerialString(fd, 1024);
					Log.d(TAG,"end");
					if(buff != null){
						Message msg = new Message();
                        msg.what = 1;
                        handler.sendMessage(msg);
            			timer = new Timer();
            			timer.schedule(new MyTask(), 60000);
					}else{
						Message msg = new Message();
                        msg.what = 0;
                        handler.sendMessage(msg);
					}
				} catch (SecurityException e) {
					e.printStackTrace();
				} catch (UnsupportedEncodingException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
    }
}
